package Tracker.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import Tracker.server.control.ProtocolHandler;
import Tracker.server.model.Model;

public class ClientHandler extends Thread {
	Model model;
	public final Socket socket;
	Server server;
	ProtocolHandler handler;

	BufferedReader in;
	PrintWriter out;

	boolean running;

	public ClientHandler(Model m, Socket s, Server srv) throws IOException {
		this.model = m;
		this.socket = s;
		this.server = srv;
		this.handler = new ProtocolHandler(this.model, this);

		this.in = new BufferedReader(new InputStreamReader(
				this.socket.getInputStream()));
		this.out = new PrintWriter(this.socket.getOutputStream(), true);

		this.running = true;
	}

	@Override
	public void run() {
		System.out.println("Client "
				+ this.socket.getInetAddress().getHostAddress() + ":"
				+ this.socket.getPort() + " Connected");

		try {
			while (this.running) {
				System.out.println("Server read line");
				String request = this.in.readLine();
				System.out.println("Server: <-- " + request);
				if (request == null) { // Connection Closed!
					this.running = false;
				} else {
					String response = this.handler.parse(request);

					System.out.println("Server: --> " + response);
					this.out.println(response);
				}
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		try {
			this.in.close();
			this.out.close();
			this.socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		System.out.println("Client "
				+ this.socket.getInetAddress().getHostAddress()
				+ " Disconnected");
	}

	public void push(String s) {
		this.out.println(s);
	}

	public void close() {
		this.running = false;
	}
}
